<template>
  <c-dialog
    v-model="dialogVisible"
    :title="detail && detail.id ? `编辑` : `新建`"
    :width="'700px'"
    :before-close="handleClose">
    <el-form :model="form" :rules="rules" class="album-dialog-form" label-position="top" ref="formRef">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱地址" size="large" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入备注" size="large" />
      </el-form-item>
    </el-form>
    <template #action>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </template>
  </c-dialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, watch } from 'vue';
import { type FormRules } from 'element-plus';
import http from '@/utils/http'
import { useMessage } from '@/utils/utils';
import type { ReceiverInter } from '@/typings/interface';

/**
 * 实例
 */
interface Props {
  modelValue: boolean
  detail?: ReceiverInter | null
  author_type?: 'answer' | 'publisher'
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  detail: () => ({} as ReceiverInter)
})
const emit = defineEmits(['update:modelValue', 'submit'])

/**
 * 变量
 */
const dialogVisible = computed({
  get () {
    return props.modelValue
  },
  set (val) {
    emit('update:modelValue', val)
  }
})
const form: ReceiverInter = reactive({
  email: '',
  remark: '',
})
const rules: FormRules = reactive({
  email: [
    { required: true, message: '请输入邮箱地址', trigger: ['blur', 'change'] }
  ]
})
// 表单ref
const formRef = ref(null)

/**
 * 回调函数
 */
// 关闭窗口
const handleClose = () => {
  dialogVisible.value = false
}
// 提交
const submit = () => {
  // @ts-ignore
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      if (form.id) {
        itemUpdate()
      } else {
        itemCreate()
      }
    }
  })
}
// 创建
const itemCreate = () => {
  http('/author/receiver/create', {
    ...form
  }).then(res => {
    useMessage('创建成功')
    handleClose()
    emit('submit')
  })
}
// 更新
const itemUpdate = () => {
  http('/author/receiver/update', {
    ...form
  }).then(res => {
    useMessage('更新成功')
    handleClose()
    emit('submit')
  })
}

/**
 * 监听器
 */
watch(() => props.detail, (val: ReceiverInter | null) => {
  if (val) {
    for (let key in val) {
      // @ts-ignore
      form[key] = val[key]
    }
  }
}, {
  immediate: true
})
</script>

<style lang="scss">
.album-dialog-form {
  width: 100%;
  margin-bottom: 10px;
}
</style>